package logic

import (
	"context"
	"errors"
	"shop-cart/cache"
	"shop-cart/models"

	"shop-cart/taobaorpc/internal/svc"
	"shop-cart/taobaorpc/taobaorpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type CarAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCarAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CarAddLogic {
	return &CarAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CarAddLogic) CarAdd(in *taobaorpc.CarAddRequest) (*taobaorpc.CarAddResponse, error) {
	// todo: add your logic here and delete this line
	var user models.User
	data, err := user.FindUserById(models.DB, in.UserId)
	if err != nil {
		return nil, err
	}
	if data.ID == 0 {
		return nil, errors.New("用户不存在")
	}
	var products models.Product
	product, err := products.FindProductById(models.DB, in.ProductId)
	if err != nil {
		return nil, err
	}
	if product.ID == 0 {
		return nil, errors.New("此商品不存在")
	}
	if in.Number > product.Stock {
		return nil, errors.New("您购买的数量超过了库存数量请重新购买")
	}
	exists, err := cache.FindProductExists(in.UserId, in.ProductId)
	if err != nil {
		return nil, err
	}
	if exists == 0 {
		mapData := map[string]interface{}{
			"userId":    in.UserId,
			"productId": in.ProductId,
			"number":    in.Number,
			"title":     product.Title,
			"price":     product.Price,
			"image":     product.Image,
		}
		if err = cache.CarAdd(in.UserId, in.ProductId, mapData); err != nil {
			return nil, errors.New("购物车添加失败")
		}
	} else {

		if err = cache.UpdateCartProductNumber(in.UserId, in.ProductId, in.Number); err != nil {
			return nil, errors.New("修改购物车中商品数量失败")
		}
	}
	return &taobaorpc.CarAddResponse{
		ProductId: int64(product.ID),
	}, nil
}
